package com.schx.budget.filter;

import com.schx.budget.util.JwtUtil;
import io.jsonwebtoken.Claims;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname LoginFilter
 * @Description TODO
 * @Date 2021/2/5 11:45
 * @Created by cyh
 */
@WebFilter(urlPatterns = "/*", filterName = "LoginFilter")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {


        String url = ((HttpServletRequest) req).getRequestURI();
        //直接放行
        if(url.contains("subLogin")){
            filterChain.doFilter(req,response);
        }

        //验证token
        String token = ((HttpServletRequest) req).getHeader("token");
        boolean flag=true;
        //未携带token
        if("".equalsIgnoreCase(token)||token==null){
            flag=false;
            ServletOutputStream out = response.getOutputStream();
            try {
                String ciphertext = "{\"code\":"+403+" ,\"data\":\"未登录!\"}";
                out.write(ciphertext.getBytes());
                out.flush();
            }finally {
                out.close();
            }

        }
        try {
            //校验token
            Claims claims = JwtUtil.parseJwt(token);
            Map user = (HashMap) claims.get("data");
        }catch(Exception e){
            ServletOutputStream out = response.getOutputStream();
            flag=false;
            try {
                String ciphertext = "{\"code\":"+403+" ,\"data\":\"登录信息过期!\"}";
                out.write(ciphertext.getBytes());
                out.flush();
            }finally {
                out.close();
            }
        }

        if(flag) {
            filterChain.doFilter(req, response);
        }
    }

    @Override
    public void destroy() {

    }
}
